import { logger } from '../logger/Logger';

export class EmailAddress {
  name: string
  email: string
}
export function isTheSameEmailAddress(a: EmailAddress, b: EmailAddress):boolean {
  return a.name == b.name && a.email == b.email
}

export function parseEmailAddress(s:string):EmailAddress|undefined {
  let addr:EmailAddress = undefined;
  let s1 = s.replace(";","");
  if(s1.search("@") != -1) {
    let coms = s1.split("@");
    addr = {
      name:coms[0],
      email:s1
    }
  }
  else {
    addr = {
      name:s1,
      email:s1
    }
  }
  return addr;
}
/*
简单解析邮件地址
CAVEAT: 当名字里面有特殊字符<,;时会出错
*/
export function parseEmailAddresses(s: string): EmailAddress[] {
  if (!s || !s.trim()) {
    return [];
  }
  try {
    return s.split(/[,;]/).map(s => {
      s = s.trim();
      const i = s.indexOf("<");
      if (i == -1) {
        return { name: "", email: s };
      } else {
        let name = s.substring(0, i).trim();
        if (name.startsWith('"') && name.endsWith('"')) {
          name = name.substring(1, name.length - 1);
        }
        return {
          name,
          email: s.substring(i + 1, s.length - 1).trim(),
        };
      }
    });
  } catch (e) {
    logger.error("parseAddress error", s, e);
    return [];
  }
}

// 登录协议
export enum EmailFetchProtocol {
  POP3 = "pop3",
  IMAP = "imap",
  COREMAIL = "coremail",
  EXCHANGE = "exchange"
}

// 发信协议
export enum EmailSendProtocol {
  SMTP = "smtp",
  COREMAIL = "coremail",
  EXCHANGE = "exchange"
}

/* 设置相关属性 */
export type HostConfig = {
  password: string,
  account: string,
  host: string;
  port: number;
  secure: boolean,
}

export type UserConfig = {
  password: string,
  account: string,
  fetchProtocol: EmailFetchProtocol,
  sendProtocol: EmailSendProtocol
}

export type EmailProperties = {
  // 发信相关属性
  // 服务器相关的属性，imap/pop3 只需要填一个，smtp必填
  imap?: HostConfig;
  pop3?: HostConfig;
  smtp?: HostConfig;
  coremail?: HostConfig;
  oauth2?: string;
  // 用户账号信息
  userInfo: UserConfig;
  // 其他属性
  extra?: {
    [prop: string]: string | boolean | number;
  };
  exchange?: {
    url: string,
    secure: boolean,
    oauthToken?: string,
    type: 'Basic' | 'Ntlm' | 'OAuth'
  };
  ca?: string[]
};

// export type EmailAddress = {
//   name: string;
//   email: string;
// };

export function encodeAddress(address: EmailAddress): string {
  if (!address.name) {
    return address.email;
  }
  return `${encodeMimeString(address.name)} <${address.email}>`;
}

export function encodeAddressList(addressList: EmailAddress[]): string {
  return addressList.map(addr => encodeAddress(addr)).join(';\r\n\t');
}
export function cmReceiverFormat(address: EmailAddress) {
  if (!address.name) {
    return address.email
  }
  return `${address.name} <${address.email}>`
}

export function encodeMimeString(s: string, qpThreshold = 0.7): string {
  return s;
  // const m = getEncodeMethod(s, qpThreshold);
  // if (m == "") {
  //   return s;
  // }
  // const useQP = m == "Q";
  // const prefix = useQP ? "=?UTF-8?Q?" : "=?UTF-8?B?";
  // let r = useQP ? qpEncode(s, -1) : base64Encode(s, -1);
  // if (r.length <= 50) {
  //   r = prefix + r + "?=";
  // } else {
  //   const res = [];
  //   let len = 0;
  //   let b = 0;
  //   for (let i = 0; i < s.length; i++) {
  //     const v = s.charCodeAt(i);
  //     if (v == 0x3d || v <= 0x20 || v >= 0x7e) {
  //       len += useQP ? 9 : 4; // chinese char
  //     } else {
  //       len += 1.3;
  //     }
  //     if (len >= 50 || i == s.length - 1) {
  //       if (i == s.length - 1) {
  //         i += 1;
  //       }
  //       const subStr = s.substring(b, i);
  //       res.push(
  //         prefix +
  //           (useQP ? qpEncode(subStr, -1) : base64Encode(subStr, -1)) +
  //           "?="
  //       );
  //       b = i;
  //       len = 0;
  //     }
  //   }
  //   r = res.join("\r\n\t");
  // }
  // return r;
}